namespace RBAC.Read.Api.Controllers.ProcessManagements
{
    using Microsoft.AspNetCore.Mvc;
    using RBAC.Read.Api.Application.Dto;
    using RBAC.Read.Api.Application.Interfaces;
    using RBAC.ErrorCode;

    /// <summary>
    /// 生产工单（读侧）控制器：列表与详情。
    /// </summary>
    [ApiController]
    [Route("api/process-management/production-work-orders")]
    public class ProductionWorkOrdersController : ControllerBase
    {
        private readonly IProductionWorkOrderReadService _svc;
        public ProductionWorkOrdersController(IProductionWorkOrderReadService svc)
        {
            _svc = svc;
        }

        /// <summary>
        /// 生产工单列表查询。
        /// </summary>
        [HttpGet]
        public IActionResult GetList([FromQuery] WorkOrderListFilterDto filter)
        {
            var res = _svc.GetProductionWorkOrderList(filter);
            return Ok(res);
        }

        /// <summary>
        /// 生产工单详情。
        /// </summary>
        [HttpGet("{orderCode}")]
        public IActionResult GetDetail([FromRoute] string orderCode)
        {
            var res = _svc.GetProductionWorkOrderDetail(orderCode);
            return Ok(res);
        }

        /// <summary>
        /// 导出生产工单列表（Excel）。
        /// </summary>
        [HttpGet("export")]
        public IActionResult Export([FromQuery] WorkOrderListFilterDto filter)
        {
            var result = _svc.ExportProductionWorkOrders(filter);
            if (result.Code == APIEnums.Success && result.Data != null && result.Data.Length > 0)
            {
                var ts = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                var fileName = $"生产工单_{ts}.xlsx";
                const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                return File(result.Data, contentType, fileName);
            }
            return BadRequest(result);
        }
    }
}
